//
//  VRMyInfoViewController.m
//  VRFirefighting
//
//  Created by Veer on 2018/8/15.
//  Copyright © 2018年 Veer. All rights reserved.
//

#import "VRMyInfoViewController.h"

#import "JKPersonInfoCell.h"
#import "JKSelectorView.h"
#import "JKPersonInfoConfigModel.h"

#import "NSString+Tools.h"

@interface VRMyInfoViewController () <UITableViewDataSource, UITableViewDelegate>

@property (nonatomic, strong) UITableView *tableView;

@property (nonatomic, strong) NSMutableArray<NSMutableArray<JKPersonInfoConfigModel *> *> *sectionArray;

@property (nonatomic, weak) UITextField *curSelectedTextFeild;
@property (nonatomic, strong) NSIndexPath *curSelectedIndexPath;

@property (nonatomic, weak) UITextField *captchaTextFeild;

@end

@implementation VRMyInfoViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.title = @"我的信息设置";
    self.view.backgroundColor = ScrollViewBgColor;
    
    [self.view addSubview:self.tableView];
    [self setupSubView];
    [self getMyInfo];
}

- (void)setupSubView
{
    UIView *footerView = [[UIView alloc] init];
    footerView.frame = CGRectMake(0, 0, kScreenWidth, 70);
    self.tableView.tableFooterView = footerView;
    
    // 按钮
    UIButton *loginBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    loginBtn.backgroundColor = RGB(78, 173, 57);
    loginBtn.layer.cornerRadius = 4;
    [loginBtn setTitle:@"保存" forState:UIControlStateNormal];
    loginBtn.titleLabel.font = VRFont(16);
    [loginBtn setTitleColor:RGB(255, 255, 255) forState:UIControlStateNormal];
    [loginBtn setTitleColor:RGB(120, 120, 120) forState:UIControlStateHighlighted];
    [loginBtn addTarget:self action:@selector(onSaveBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    [footerView addSubview:loginBtn];
    [loginBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(footerView);
        make.bottom.mas_equalTo(footerView);
        make.width.mas_equalTo(100);
        make.height.mas_equalTo(44);
    }];
}


#pragma mark - networking
- (void)getMyInfo
{
    
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    param[@"UserID"] = [VRUser shareUser].token;
    
    weakify(self)
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    [JKNetworking postWithSign:GetMyInfo parameters:param success:^(NSDictionary *responseObject) {
        
        strongify(self)
        NSLog(@"responseObject:%@", responseObject);
        NSInteger code = [responseObject[@"state"] integerValue];
        NSString *msg = responseObject[@"message"];
        
        if (code == 0) {
            
            self.sectionArray[0][0].value = responseObject[@"data"][@"fPhone"];
            self.sectionArray[0][1].value = responseObject[@"data"][@"fPhone1"];
            self.sectionArray[0][2].value = responseObject[@"data"][@"fPhone2"];
            self.sectionArray[0][3].value = responseObject[@"data"][@"fPhone3"];
            dispatch_async(dispatch_get_main_queue(), ^{
                
                [self.tableView reloadData];
                [hud hideAnimated:YES];
            });
        }else if(msg.length > 0){
            dispatch_async(dispatch_get_main_queue(), ^{
                [SVProgressHUD showErrorWithStatus:msg];
                [hud hideAnimated:YES];
            });
        }
    } error:^(NSError * _Nonnull error) {
        dispatch_async(dispatch_get_main_queue(), ^{
            [SVProgressHUD showErrorWithStatus:@"未知错误"];
            [hud hideAnimated:YES];
        });
    }];
}


- (void)saveMyInfo
{
    
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    param[@"UserID"] = [VRUser shareUser].token;
    param[@"phone1"] = self.sectionArray[0][1].value.length > 0 ? self.sectionArray[0][1].value : @" ";
    param[@"phone2"] = self.sectionArray[0][2].value.length > 0 ? self.sectionArray[0][2].value : @" ";
    param[@"phone3"] = self.sectionArray[0][3].value.length > 0 ? self.sectionArray[0][3].value : @" ";
    
    weakify(self)
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    [JKNetworking postWithSign:UpdateMyInfo parameters:param success:^(NSDictionary *responseObject) {
        
        strongify(self)
        NSLog(@"responseObject:%@", responseObject);
        NSInteger code = [responseObject[@"state"] integerValue];
        NSString *msg = responseObject[@"message"];
        
        if (code == 0) {
            
            dispatch_async(dispatch_get_main_queue(), ^{
                
                [hud hideAnimated:YES];
                [SVProgressHUD showSuccessWithStatus:@"保存成功"];
            });
            
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                
                [self.navigationController popViewControllerAnimated:YES];
            });
            
        }else if(msg.length > 0){
            dispatch_async(dispatch_get_main_queue(), ^{
                [SVProgressHUD showErrorWithStatus:msg];
                [hud hideAnimated:YES];
            });
        }
    } error:^(NSError * _Nonnull error) {
        dispatch_async(dispatch_get_main_queue(), ^{
            [SVProgressHUD showErrorWithStatus:@"未知错误"];
            [hud hideAnimated:YES];
        });
    }];
}


#pragma mark - action
- (void)onSaveBtnClick:(UIButton *)sender
{
    if (self.sectionArray[0][1].value.length > 0 && [NSString valiMobile:self.sectionArray[0][1].value]) {
        [SVProgressHUD showErrorWithStatus:@"请输入正确的备用电话1"];
        return;
    }
    if (self.sectionArray[0][2].value.length > 0 && [NSString valiMobile:self.sectionArray[0][2].value]) {
        [SVProgressHUD showErrorWithStatus:@"请输入正确的备用电话2"];
        return;
    }
    if (self.sectionArray[0][3].value.length > 0 && [NSString valiMobile:self.sectionArray[0][3].value]) {
        [SVProgressHUD showErrorWithStatus:@"请输入正确的备用电话3"];
        return;
    }
    
    [self saveMyInfo];
}



#pragma mark - delegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return self.sectionArray.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (section == 2) {
        return 44;
    }
    return 0.01;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    return nil;
}


- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 10;
}

- (NSString *)tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section
{
    return @" ";
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    
    NSMutableArray *modelArray = self.sectionArray[section];
    return modelArray.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 50;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSMutableArray *modelArray = self.sectionArray[indexPath.section];
    JKPersonInfoConfigModel *model = modelArray[indexPath.row];
    
    JKPersonInfoCell *cell = [JKPersonInfoCell cellWith:tableView];
    cell.model = model;
    
    weakify(self)
    cell.textFieldClickBlock = ^(UITextField *textField) {
        
        strongify(self)
        
        self.curSelectedTextFeild = textField;
        self.curSelectedIndexPath = indexPath;
        
        //        if (indexPath.section == 1 && indexPath.row == 0) {
        //
        //            [self.view endEditing:YES];
        //            [self.areaSelectorView show];
        //            return;
        //        }
        
        if (!model.isCanEdit) {
            [self.view endEditing:YES];
        }
        
        if (model.performName.length > 0) {
            
            [self.view endEditing:YES];
            if ([self respondsToSelector:NSSelectorFromString(model.performName)]) {
                
                dispatch_async(dispatch_get_main_queue(), ^{
                    [self performSelector:NSSelectorFromString(model.performName) withObject:nil];
                });
            }
        }
    };
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    NSMutableArray *modelArray = self.sectionArray[indexPath.section];
    JKPersonInfoConfigModel *model = modelArray[indexPath.row];
}


#pragma mark - lazy
- (UITableView *)tableView
{
    if (_tableView == nil) {
        
        _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 0.01)];
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.estimatedRowHeight = 0;
        _tableView.estimatedSectionHeaderHeight = 0;
        _tableView.estimatedSectionFooterHeight = 0;
        _tableView.sectionHeaderHeight = 0;
        _tableView.sectionFooterHeight = 0;
        _tableView.keyboardDismissMode = UIScrollViewKeyboardDismissModeOnDrag;
        [self.view addSubview:self.tableView];
        [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.mas_equalTo(self.view);
            make.top.mas_equalTo(0);
            make.bottom.mas_equalTo(0);
        }];
        
        
//        UIView *headerView = [[UIView alloc] init];
//        headerView.frame = CGRectMake(0, 0, kScreenWidth, 20);
        
        //        UIImageView *topImgView = [[UIImageView alloc] init];
        //        topImgView.contentMode = UIViewContentModeScaleAspectFit;
        //        topImgView.image = [UIImage imageNamed:@"icon_base_info"];
        //        topImgView.frame = CGRectMake(0, 16, kScreenWidth, 112 - 16);
        //        [headerView addSubview:topImgView];
        
//        _tableView.tableHeaderView = headerView;
    }
    return _tableView;
}


- (NSMutableArray<NSMutableArray<JKPersonInfoConfigModel *> *> *)sectionArray
{
    if (_sectionArray == nil) {
        
        NSArray *titleArray = @[@"我的电话", @"备用电话1", @"备用电话2", @"备用电话3"];
        NSMutableArray *modelArray = [NSMutableArray array];
        for (int i = 0; i < titleArray.count; i++) {
            
            JKPersonInfoConfigModel *model = [[JKPersonInfoConfigModel alloc] init];
            model.isCanEdit = i > 0;
            model.isHideAccessory = YES;
            model.name = titleArray[i];
            model.des = @"请输入您的备用号码";
            [modelArray addObject:model];
        }
        _sectionArray = [NSMutableArray array];
        [_sectionArray addObject:modelArray];
        
        NSLog(@"");
    }
    return _sectionArray;
}



@end
